package springjunit;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.util.Arrays;
import java.util.List;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.CachedDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.stream.IDataSetProducer;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.dataset.xml.FlatXmlProducer;
import org.dbunit.operation.DatabaseOperation;
import org.xml.sax.InputSource;

public class DatabaseHelper {
	public static boolean cleanTables(Connection connection, List<String> tableNameList) throws Exception {
		boolean result =false;
		String sql = "delete from ";
		if (tableNameList != null) {
			for (String tableName : tableNameList) {
				String tempSql = sql + tableName;
				System.out.println("Will executing " + tempSql);
				connection.createStatement().execute(tempSql);
			}
			result = true;
		}
		return result;
	}
	
	public static boolean cleanTables(Connection connection, String... tableNameList) throws Exception {
		boolean result =false;
		if (tableNameList != null) {
			return cleanTables(connection, Arrays.asList(tableNameList));
		}
		return result;
	}
	
	public static void loadData(Connection connection, String fileName) throws Exception{
		File f = new File(fileName);
		if(f.exists()==false){
			throw new IllegalArgumentException("找不到数据文件 " + fileName);
		}
		IDatabaseConnection	conn = new DatabaseConnection(connection);
		// is.setEncoding("GBK");   
		IDataSetProducer producer;   
		IDataSet dataSet;   
		producer = new FlatXmlProducer(new InputSource(fileName));   
		dataSet = new CachedDataSet(producer);   
		// 执行插入操作   
		DatabaseOperation.REFRESH.execute(conn, dataSet);    
		//IDataSet ds = loader.load("/the/package/prepData.xml");
	}
	
	public static void dumpData(Connection jdbcConnection, String...tableNameList) throws Exception{
		// Get a JDBC connection
		StringBuilder fileName = new StringBuilder("dataFOf[");
        IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
        QueryDataSet partialDataSet = new QueryDataSet(connection);
        for(String tableName: tableNameList){
        	partialDataSet.addTable(tableName);
        	fileName.append(tableName).append(",");
        }
        fileName.append("]");
        FlatXmlDataSet.write(partialDataSet, new FileOutputStream(fileName.toString()));
	}
}
